﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Entitys.MesMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.TibcoMessage;
using HamcoWcs.Service.Common;
using System.Xml;

namespace HamcoWcs.Service.Mes.Parsers
{
    /// <summary>
    /// 切换方向（出入库模式）事件
    /// </summary>
    public class MesMsgParser_MachineModeChangeRequest : MesMsgParserBase
    {

        private readonly IPconBaseService _pconBaseService;
        private readonly IMesCommunicateService _mesCommunicateService;

        public MesMsgParser_MachineModeChangeRequest(ILoggerService logger,WcsDbContext wcsDbContext, IMapper mapper, IPconBaseService pconBaseService, IMesCommunicateService mesCommunicateService) 
            : base(logger, wcsDbContext, mapper)
        {
            _pconBaseService = pconBaseService;
            _mesCommunicateService = mesCommunicateService;
        }

        public override string EventName => "MACHINEMODECHANGEREQUEST";

        public override void HandleEvent(MesMsgQueue message)
        {
            //var msg = XmlHelper.Deserialize<MachineModeChangeMessage>(message.Return);
            //string code = XmlHelper.GetXPathText(message.Return, "//RETURNCODE");

            //string machineName = msg.Body.LineName;
            //string portName = msg.Body.PortName;
            //var pcon = _pconBaseService.GetPcon(machineName, portName);

            //if (pcon == null) return;

            //var mode = msg.Body.LineOperMode;
            //PconSendMsg pconSendMsg;
            //if (code == "0")
            //{
            //    pconSendMsg = new PconSendMsg()
            //    {
            //        PconName = (ushort)pcon.PconName,
            //        Request = (ushort)(mode == "IN" ? EnumPconSendMsg.ChangeInModeCmd : EnumPconSendMsg.ChangeOutModeCmd)
            //    };
            //    if (mode == "OUT" && pcon.PconType == EnumPconType.Wharf)
            //    {
            //        pcon.PortState = "LR";
            //        _mesCommunicateService.PortTransferStateChanged(pcon);
            //    }
            //    _logger.AddWcsRunLog("", $"{pcon.DeviceName},MES同意切换模式");

            //}
            //else
            //{
            //    // 拒绝切方向
            //    pconSendMsg = PconSendMsg.CreateRejectChangeModeMsg(pcon);
            //    _logger.AddWcsRunLog("", $"{pcon.DeviceName},MES拒绝切换模式");
            //}

            //var deviceMsgQueueDto = new DeviceMsgQueueDto(pcon, pconSendMsg);
            //var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);

            //_wcsDbContext.DeviceMsgQueues.Add(deviceMsgQueue);
            //_wcsDbContext.SaveChanges();
            message.Status = (int)EnumMesMsgStatus.Completed;
        }
    }
}
